# Create your views here.

from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from django.core.mail import EmailMessage
from congreso.settings import USE_EMAIL, EMAIL_SUBJECT, EMAIL_FROM
import datetime

from congreso.trabajos.models import *
from congreso.trabajos.forms import * 

def main_page(request):
    '''Pagina de inicio'''
    variables = RequestContext(request, { 
        'user':request.user, 
    })
    return render_to_response('main.html', variables)

def logout_page(request):
    '''Cierra sesion'''
    logout(request)
    return HttpResponseRedirect('/')

   
# DISSERTATIONS

def dissertation_list(request):
    '''Listado de Trabajos'''
    if request.user.is_authenticated():
        try:
            c = Contact.objects.get(contact=request.user)
            all = Dissertation.objects.filter(sub_area=c.sub_area)
            variables = RequestContext(request, {
                'all':all,
                'sub_area':c.sub_area,
            })
            return render_to_response('dissertation_list.html', variables)
        except:
            variables = RequestContext(request, { 
                'user':request.user, 
            })
            return render_to_response('no_contact.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)
    
def dissertation_add(request):
    '''Agrega Trabajos'''
    if request.method == 'POST':
        form = DissertationForm(request.POST)
        if form.is_valid():
            p_date = form.cleaned_data['date']
            p_author_first_name = form.cleaned_data['author_first_name']
            p_author_last_name = form.cleaned_data['author_last_name']
            p_author_email = form.cleaned_data['author_email']
            p_author_phone = form.cleaned_data['author_phone']
            p_filiation = form.cleaned_data['filiation']
            p_filiation_country = form.cleaned_data['filiation_country']
            p_presenter = form.cleaned_data['presenter']
            p_main_author = form.cleaned_data['main_author']
            p_registered = form.cleaned_data['registered']
            p_area = form.cleaned_data['area']
            p_sub_area = form.cleaned_data['sub_area']
            p_language = form.cleaned_data['language']
            p_title = form.cleaned_data['title']
            p_dissertation = form.cleaned_data['dissertation']
            p_dissertation_type = form.cleaned_data['dissertation_type']
            p_status = Status.objects.filter(status='New')
            a = Area.objects.filter(area=p_area)
            s = SubArea.objects.filter(pk=p_sub_area)
            reg = Dissertation(date=p_date,author_first_name=p_author_first_name,\
                    author_last_name=p_author_last_name,author_email=p_author_email,\
                    author_phone=p_author_phone,filiation=p_filiation,filiation_country=\
                    p_filiation_country,presenter=p_presenter,main_author=p_main_author,registered=\
                    p_registered,area=a[0],sub_area=s[0],language=p_language,title=p_title,\
                    dissertation=p_dissertation,dissertation_type=p_dissertation_type,\
                    status=p_status[0])
            reg.save()
            return HttpResponseRedirect('/dissertations/email/%s/' % reg.id)
    else:
        form = DissertationForm()
    variables = RequestContext(request, { 'form':form })
    return render_to_response('dissertation_add.html', variables)

def dissertation_confirm(request):
    '''Confirmacion de trabajo ingresado'''
    variables = RequestContext(request, { 
        'user':request.user, 
    })
    return render_to_response('dissertation_add_confirm.html', variables)

def send_mail(request, dissertation_id):
        '''Envia correo'''
        d = Dissertation.objects.get(pk=dissertation_id)
        variables = RequestContext(request, {
            'dissertation':d,
        })
        if USE_EMAIL:
            email_html_content = render_to_response('mail_content.html', variables)
            email_html_content = email_html_content.content.replace('Content-Type: text/html; charset=utf-8','')
            inner_qs = SubArea.objects.filter(sub_area=d.sub_area).values('sub_area')
            recipients = Contact.objects.filter(sub_area__sub_area__in=inner_qs)
            EMAIL_ADDRESS = []
            for i in recipients:
                ADDRESS.append(i.contact.email)
            email = EmailMessage(EMAIL_SUBJECT,email_html_content,EMAIL_FROM,EMAIL_ADDRESS)
            email.content_subtype = "html"
            email.send()
            return HttpResponseRedirect('/dissertations/confirm/')
        else:
            return HttpResponseRedirect('/dissertations/confirm/')
    
def dissertation_show(request, dissertation_id):
    '''Muestra datos del Trabajo seleccionado'''
    if request.user.is_authenticated():
        disert = Dissertation.objects.get(pk=dissertation_id)
        us = request.user
        c = Contact.objects.get(contact=us)
        if request.method == 'POST':
            form = CommentForm(request.POST)
            if form.is_valid():
                reg = form.save()
                reg.dissertation = disert
                reg.save()
                if c:
                    reg.author = c
                    reg.save()
                reg.date_time = datetime.datetime.now()
                reg.save()
                return HttpResponseRedirect('/dissertations/show/%s/' % dissertation_id)
        else:
            form = CommentForm()
        com = Comment.objects.filter(dissertation=disert)
        variables = RequestContext(request, {
            'form':form,
            'dissertation':disert,
            'com':com,
        })
        return render_to_response('dissertation_show.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)

def get_sub_areas(request, area_id):
    a = Area.objects.filter(pk=area_id)
    sub_areas = SubArea.objects.filter(area=a[0])
    variables = RequestContext(request, {'sub_areas' : sub_areas })
    return render_to_response ('get_sub_areas.html', variables)


